package com.abs.orm.db.jdbc.provider;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import com.abs.orm.db.jdbc.JdbcType;

public class ConnectionProvider {
	private Connection connection;
	private DBConfig dbConfig = null;
	private static Map<JdbcType, ConnectionProvider> connectionProviders = new HashMap<JdbcType, ConnectionProvider>(0);

	private ConnectionProvider() {
		super();
	}

	public static ConnectionProvider getInstance(JdbcType jdbcType) {
		ConnectionProvider connectionProvider = connectionProviders.get(jdbcType);
		if (null == connectionProvider) {
			connectionProvider = new ConnectionProvider();
			if (jdbcType == JdbcType.MySQL) {
				connectionProvider.registerDBConfig(DBConfig.MySQL);
			}
			if (jdbcType == JdbcType.Oracle) {
				connectionProvider.registerDBConfig(DBConfig.Oracle);
			}
			if (jdbcType == JdbcType.SQLServer) {
				connectionProvider.registerDBConfig(DBConfig.SQLServer);
			}
		}
		return connectionProvider;
	}

	private void registerDBConfig(DBConfig dbConfig) {
		if (null == dbConfig) {
			this.dbConfig = DBConfig.MySQL;
		} else {
			this.dbConfig = dbConfig;
		}
		registerDriverClass();
	}

	private void registerDriverClass() {
		try {
			Class.forName(dbConfig.getDriverClassName());
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	public Connection getConnection() {
		try {
			if (connection == null || connection.isClosed()) {
				try {
					connection = DriverManager.getConnection(dbConfig.getUrl(), dbConfig.getUsername(), dbConfig.getPassword());
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return connection;
	}

	public void close() {
		if (null != connection) {
			try {
				connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
}
